import {defineStore, storeToRefs} from "pinia";
import {useWebSocket, UseWebSocketReturn,} from '@vueuse/core'
import {wsUrl, loginPrefixUrl, loginPrefixParams} from '~/settings'
import {useUserStore} from "@/store/user";

export const useWebSocketStore = defineStore('webSocket', {
    persist: true,
    state: () => {
        return {
            ws: {} as UseWebSocketReturn<any>,
            loginUrl: '',
        }
    },
    /**
     * 封装计算属性，有缓存功能
     */
    getters: {},
    /**
     * 封装业务逻辑，修改state
     */
    actions: {
        connect() {
            //@ts-ignore
            this.ws = useWebSocket(wsUrl, {
                heartbeat: {
                    message: JSON.stringify({
                        type: 'heartbeat',
                        data: 'ping'
                    } as IWSReq),
                    interval: 10000,
                    pongTimeout: 1000,
                },
                autoReconnect: true,
                onConnected: () => {

                },
                onMessage: () => {
                    const response = JSON.parse(this.ws.data) as IWSRes
                    if (response.msg === 'WS心跳检测') {
                        this.handleHeartbeatResponse(response)
                    } else if (response.msg === 'WS请求登录') {
                        this.handleLoginResponse(response)
                    } else if (response.msg === 'WS登录成功') {
                        this.handleLoginSuccessResponse(response)
                    } else if (response.msg === 'WS用户验证') {
                        this.handleAuthorizationResponse(response)
                    }
                },
            })
        },
        send(val: IWSReq) {
            this.ws.send(JSON.stringify(val))
        },

        loginReq() {
            this.send({
                type: 'login',
            })
        },
        authenticationReq() {
            const {token} = storeToRefs(useUserStore())
            this.send({
                type: 'authorization',
                data: token.value,
            })
        },
        handleHeartbeatResponse(response: IWSRes) {
            console.log(response.msg)
        },
        handleLoginResponse(response: IWSRes) {
            const q = loginPrefixParams + response.data
            this.loginUrl = loginPrefixUrl + q
        },
        handleLoginSuccessResponse(response: IWSRes) {
            const userStore = useUserStore()
            userStore.successLogin(response.data.userInfo, response.data.token, response.data.refreshToken)
            window.$message.success('登录成功')
        },
        handleAuthorizationResponse(response: IWSRes) {
            const userStore = useUserStore()
            if (response.data === false) {
                userStore.logout()
                window.$message.error('用户未登录')
            }
        },


    },
})
